﻿using JobSearcherAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace JobSearcherAPI.Search
{
    internal abstract class XmlSearcher : SearcherBase
    {
        protected XmlDocument doc = new XmlDocument();
        protected XmlNodeList nodes;

        protected abstract override string CreateSearchAddress(SearchArguments arguments);
        protected abstract override void SetUpAttributeStrings();
        protected abstract XmlNodeList GetJobNodes();

        public XmlSearcher()
        {
            SetUpAttributeStrings();
        }

        public override async Task<SearchResult> Search(SearchArguments arguments)
        {
            var result = new SearchResult();
            searchAddress = CreateSearchAddress(arguments);

            Uri addressUri = new Uri(searchAddress);

            using (var client = new WebClient())
            {
                client.DownloadStringCompleted += (sender, e) =>
                {
                    doc.LoadXml(e.Result);
                    nodes = GetJobNodes();
                    foreach (XmlNode n in nodes)
                    {
                        var job = new Job
                        {
                            Title = n.SelectSingleNode(title).InnerText,
                            Company = n.SelectSingleNode(company).InnerText,
                            Location = n.SelectSingleNode(location).InnerText,
                            Description = n.SelectSingleNode(description).InnerText,
                            PostDate = DateTime.Parse(n.SelectSingleNode(date).InnerText),
                            PostURL = n.SelectSingleNode(url).InnerText
                        };
                        result.Add(job);
                    }
                };

                await client.DownloadStringTaskAsync(addressUri);
                return result;
            }
        }
    }
}
